package com.wuyou.sso2.component;

import cn.hutool.core.util.ArrayUtil;
import com.wuyou.sso.common.contant.AuthConstants;
import com.wuyou.sso.common.entity.Menu;
import com.wuyou.sso.common.entity.User;
import com.wuyou.sso.common.enums.MenuTypeEnum;
import com.wuyou.sso2.handler.login.LoginHandlerFactory;
import com.wuyou.sso2.userdetails.CustomizedUser;
import com.wuyou.sso2.userdetails.TenantVO;
import com.wuyou.sso2.vo.UserVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 用户详细信息
 *
 * @author lishangbu
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class CustomizedUserDetailsServiceImpl implements UserDetailsService {

    /**
     * 登录处理器工厂
     */
    private final LoginHandlerFactory loginHandlerFactory;

    /**
     * 用户密码登录
     *
     * @param username 登录账号标识，格式为登录凭证@登录类型
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        UserVO userVO = loginHandlerFactory.handle(username);
        if (userVO == null) {
            // 不管什么原因查询不到对应值，从安全角度而言都先欺骗一下调用方用户名或密码错误
            throw new BadCredentialsException("用户名或密码错误");
        }
        if (userVO.getUserInfo() == null) {
            throw new BadCredentialsException("用户名或密码错误");
        }
        Set<String> dbAuthsSet = new HashSet<>();
        if (ArrayUtil.isNotEmpty(userVO.getRoleIds())) {
            // 获取角色
            userVO.getRoleIds().stream().forEach(ele -> dbAuthsSet.add(AuthConstants.ROLE + ele));
            // 获取资源
            dbAuthsSet.addAll(userVO.getMenus().stream().filter(data -> MenuTypeEnum.BUTTON.equals(data.getType())).map(Menu::getPermission).collect(Collectors.toSet()));

        }
        Collection<? extends GrantedAuthority> authorities = AuthorityUtils
                .createAuthorityList(dbAuthsSet.toArray(new String[0]));
        User user = userVO.getUserInfo();
        // 构造security用户
        CustomizedUser customizedUser =
            new CustomizedUser(user.getId(), user.getDeptId(), user.getUsername(), user.getPassword(), user.getMobile(),
                true, true, true, true, authorities, user.getDisplayName(), userVO.getTenantList());
        customizedUser.setTenantId(userVO.getTenantId());
        customizedUser.setTenantName(userVO.getTenantName());
        customizedUser.setCompanyCode(userVO.getCompanyCode());
        TenantVO vo = new TenantVO();
        //司机端无租户过滤
        if (userVO.getTenant() != null) {
            BeanUtils.copyProperties(userVO.getTenant(), vo);
            customizedUser.setTenantVO(vo);
        }
        return customizedUser;
    }
}
